<script setup lang="ts">
/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */
import {
  postRoleAll,
  postRoleAdd,
  postRoleInfo,
  postRoleDel,
  postRoleEdit,
  postBindRoutes
} from "@/api/user";

import {
  listMenus,
} from "@/api/menu";

import { formatTimestamp } from '@/utils/index'


// 获取表单
const roleFormRef = ref(ElForm);
const menuRef = ref(ElTree);

const loading = ref(false);
const dialog = reactive<DialogOption>({
  visible: false,
});

const formData = reactive<any>({
  name: '',
});

const rules = reactive({
  name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
});


const userList = ref<any>();

/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  postRoleAll()
    .then(({ data }) => {
      userList.value = data.lists;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 打开新增修改弹窗
const openDialog = (data?: any) => {
  dialog.visible = true;
  if (data) {
    Object.assign(formData, data);
    dialog.title = "修改角色";
  } else {
    dialog.title = "新增角色";
  }
}

// 删除角色
const handleDelete = (id: number) => {
  ElMessageBox.confirm("确认删除该条的数吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    postRoleDel({ ids: [id] }).then(() => {
      ElMessage.success("删除成功");
      handleQuery();
    });
  }).catch(() => ElMessage.info("已取消删除"));
}

// 提交数据
const handleSubmit = () => {
  roleFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      if (formData.id) {
        postRoleEdit(formData).then((res: any) => {
          ElMessage.success(res.msg);
          closeDialog();
          handleQuery();
        })
      } else {
        postRoleAdd(formData).then((res: any) => {
          ElMessage.success(res.msg);
          closeDialog();
          handleQuery();
        })
      }
    }
  })
}

/** 关闭表单弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/** 重置表单 */
function resetForm() {
  roleFormRef.value.resetFields();
  roleFormRef.value.clearValidate();

  formData.id = undefined;
  formData.name = '';
}

/** 重置查询 */
function resetQuery() {
  handleQuery();
}

const menuDialogVisible = ref(false);

interface CheckedRole {
  id?: number;
  name?: string;
}
let checkedRole: CheckedRole = reactive({});

// 提交权限数据
const handleRoleMenuSubmit = () => {
  const roleId = checkedRole.id;
  const checkedMenuIds: number[] = menuRef.value.getCheckedNodes(false, true).map((node: any) => node.id);

  loading.value = true;
  postBindRoutes({ id: roleId, route_ids: checkedMenuIds })
    .then((res) => {
      ElMessage.success("分配权限成功");
      menuDialogVisible.value = false;
      resetQuery();
    })
    .finally(() => {
      loading.value = false;
    });

}

const menuList = ref<any>([]);

/** 打开分配菜单弹窗 */
function openMenuDialog(row: any) {
  const roleId = row.id;
  if (roleId) {
    checkedRole = {
      id: roleId,
      name: row.name,
    };
    menuDialogVisible.value = true;
    loading.value = true;

    // 获取所有的菜单
    listMenus().then((response) => {
      menuList.value = response.data.tree;
      // 回显角色已拥有的菜单
      postRoleInfo({ id: roleId }).then(({ data }) => {
        const checkedMenuIds = data.routes;
        checkedMenuIds.forEach((menuId: any) => {
          menuRef.value.setChecked(menuId, true, false)
        });
      })
        .finally(() => {
          loading.value = false;
        });
    });
  }
}

onMounted(() => {
  handleQuery(); // 初始化用户列表数据
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :lg="24" :xs="24">
        <el-card shadow="never">
          <template #header>
            <div class="flex justify-between">
              <el-button @click="openDialog()" type="primary"><i-ep-plus />新增角色</el-button>
            </div>
          </template>
          <el-table v-loading="loading" :data="userList">
            <el-table-column label="ID" align="center" prop="id" width="100" />
            <el-table-column label="角色名称" align="center" prop="name" />
            <el-table-column label="创建时间" align="center" prop="update_time">
              <template #default="scope">
                <template v-if="scope.row.created_at > 0">
                  {{ formatTimestamp(scope.row.created_at * 1000) }}
                </template>
              </template>
            </el-table-column>
            <el-table-column fixed="right" align="center" label="操作" width="220">
              <template #default="scope">
                <el-button type="primary" link size="small" @click.stop="openDialog(scope.row)">修改</el-button>
                <el-button type="primary" link size="small" @click.stop="openMenuDialog(scope.row)">分配权限</el-button>
                <el-button type="primary" link size="small" @click.stop="handleDelete(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>


    <!-- 角色表单弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" @close="closeDialog">
      <el-form ref="roleFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配菜单弹窗  -->
    <el-dialog v-model="menuDialogVisible" :title="'【' + checkedRole.name + '】权限分配'" width="800px">
      <el-scrollbar v-loading="loading" max-height="600px">
        <el-tree ref="menuRef" node-key="id" :props="{ children: 'children', label: 'name' }" show-checkbox
          :data="menuList">
          <template #default="{ data }">
            {{ data.name }}
          </template>
        </el-tree>
      </el-scrollbar>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleRoleMenuSubmit">确 定</el-button>
          <el-button @click="menuDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
